package model

/**
 * UserImage 用户生成的资源表，
 * @Description: gorm model
 */
import (
	"fmt"
	"gpt-api/framework/db"
	"gpt-api/pkg/util"
	"time"
)

type UserImage struct {
	db.BaseModel
	UserId     uint   `json:"user_id" gorm:"column:user_id;type:int;default:0;comment:用户id"`
	ImgUrl     string `json:"img_url" gorm:"column:img_url;type:varchar(255);default:'';comment:资源地址"`
	SourceType int    `json:"source_type" gorm:"column:source_type;type:int;default:1;comment:资源类型, 1=增强图片，2=上色图片，3=生成视频时候的切片和视频"`
	HandleId   string `json:"handle_id" gorm:"column:handle_id;type:varchar(255);default:'';comment:处理id"`
	MediaType  int    `json:"media_type" gorm:"column:media_type;type:int;default:1;comment:媒体类型, 1=图片，2=视频"`
}

const (
	UserImageSourceTypeEnhance = 1
	UserImageSourceTypeColor   = 2
	UserImageSourceTypeSlice   = 3

	UserImageMediaTypeImage = 1 // 图片和member image表里 一样
	UserImageMediaTypeVideo = 2 // 视频和member image表里 一样
)

func (UserImage) TableName() string {
	return "user_image"
}

// 根据用户ID查询图片列表
func (u UserImage) GetImagesByUserId(database *db.DB, userId uint64) ([]UserImage, error) {
	var userImages []UserImage
	err := database.Model(&UserImage{}).Where("user_id = ?", userId).Find(&userImages).Error
	return userImages, err
}

// 创建用户图片
func (u *UserImage) Create(database *db.DB) error {
	return database.Create(u).Error
}

// 删除
func (u *UserImage) Delete(database *db.DB) error {
	return database.Delete(u).Error
}

func (u *UserImage) GetImageByUserIdAndPath(database *db.DB, userId uint64, path string) (UserImage, error) {
	var userImage UserImage
	err := database.Model(&UserImage{}).Where("user_id = ? and img_url = ?", userId, path).First(&userImage).Error
	return userImage, err
}

func (u *UserImage) GenerateHandleId() string {
	// sleep 1ms
	time.Sleep(time.Millisecond)
	unow := time.Now().UnixNano()
	return util.Md5(fmt.Sprintf("%d", unow))
}

func (u *UserImage) GetSourceByHandleId(database *db.DB, handleId string) ([]UserImage, error) {
	var userImages []UserImage
	err := database.Model(&UserImage{}).Where("handle_id = ?", handleId).Find(&userImages).Error
	return userImages, err
}
